<?php

class Posts extends Onecore_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model("posts_model");
        $this->_moduleName = utf8_encode("Modulo de Posts");
        $this->_moduleDescription = utf8_encode("Description") . $this->_moduleName;
        $this->_modelInstance = $this->posts_model;
    }

    public function add() {
        $success = false;
        $this->form_validation->set_rules($this->_modelInstance->getValidations());
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = $itemName . " ingresado en forma exitosa";
        $errorList = array();
        $responseData = array();
        $edit = false;
        if ($this->session) {
            $mensaje = "todo ok";
            $uid = $this->session->userdata('uid');
            $nombre = $this->session->userdata('nombre');
            if ($this->form_validation->run() == FALSE) {
                $mensaje = "Campos inválidos";
                $errorList = $this->form_validation->_error_array;
            } else {
                $this->db->trans_begin();
                $created = date('Y-m-d H:i:s');
                $extraData = array(
                    'Created'=>$created,
                    'UserId'=>$uid
                );
                $postData = array_merge($this->input->post(),$extraData);
                $data = array(
                    "id" => "",
                    "data" => $this->getInputsToSave($postData, $this->_modelInstance->getFields())
                );

                if ($this->_modelInstance->save($data, false)) {
                    
                    $responseData = array(
                        'Created'=>$created,
                        'UserId'=>$uid,
                        "nombre"=>$nombre,
                        "message"=>$this->input->post("Message")
                    );
                    $success = true;
                } else {
                    $mensaje = "El " . $itemName . " no pudo ser guardado. Verifique los siguientes errores.";
                    $errorList = array("Error" => $this->_modelInstance->getError());
                }
                if ($success) {
                    $this->db->trans_commit();
                } else {
                    $this->db->trans_rollback();
                }
            }
            $res = array(
                "success" => $success,
                "msg" => $mensaje,
                "errors" => $errorList,
                "data"=>$responseData
            );
        } else {
            $mensaje = "El usuario no posee session valida.";
        }
        $this->layout->printLike(json_encode($res), "json");
    }

    public function edit() {
        $success = false;
        $this->form_validation->set_rules($this->_modelInstance->getValidations());
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = $itemName . " editado en forma exitosa";
        $errorList = array();
        $edit = false;

        if ($this->form_validation->run() == FALSE) {
            $mensaje = "Campos inválidos";
            $errorList = $this->form_validation->_error_array;
        } else {
            $this->db->trans_begin();
            $data = array(
                "id" => $this->getFilterFieldsToEdit($this->input->post(), $this->_modelInstance->getFields()),
                "data" => $this->getInputsToSave($this->input->post(), $this->_modelInstance->getFields())
            );
            if ($this->_modelInstance->save($data, true)) {
                $success = true;
            } else {
                $mensaje = "El " . $itemName . " no pudo ser guardado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->_modelInstance->getError());
            }
            if ($success) {
                $this->db->trans_commit();
            } else {
                $this->db->trans_rollback();
            }
        }
        $res = array(
            "success" => $success,
            "msg" => $mensaje,
            "errors" => $errorList
        );
        $this->layout->printLike(json_encode($res), "json");
    }

    public function del() {
        $itemName = $this->_modelInstance->getItemName();
        $success = false;
        $mensaje = "El " . $itemName . " seleccionado no pudo ser eliminado";
        $errorList = array();
        $data = array(
            "id" => $this->getInputsToSave($this->input->post(), $this->_modelInstance->getFields())
        );
        $this->db->trans_begin();
        if ($this->_modelInstance->del($data)) {
            $success = true;
        } else {
            $errorList = array("Error" => $this->_modelInstance->getError());
        }
        if ($success) {
            $mensaje = $itemName . " eliminado en forma exitosa";
            $this->db->trans_commit();
        } else {
            $this->db->trans_rollback();
        }
        $res = array(
            "success" => $success,
            "msg" => $mensaje,
            "errors" => $errorList
        );
        $this->layout->printLike(json_encode($res), "json");
    }

    public function index() {
        $banner["module_name"] = $this->_moduleName;
        $banner["module_description"] = $this->_moduleDescription;
        $data["module_banner"] = $this->load->view("/include/sections/module_banner/module_title", $banner, true);
        $data["page_title"] = "Administración de Rols";
        $this->layout->view("/rols/index", $data);
    }

    public function loadGrid() {
        $conditions = array();
        $page = $this->input->post("page");
        $rp = $this->input->post("rp");

        $sort = $this->input->post("sortname");
        $dir = $this->input->post("sortorder");

        $query = $this->input->post("query");
        $qtype = $this->input->post("qtype");

        if (!empty($query) && $query !== "null") {
            $obj = array($qtype => $query);
            $fields = $this->_modelInstance->getFields();
            $conditionsFields = $this->_modelInstance->getFieldsConditions();
            $conditions = $this->getConditionsByObject($obj, $conditionsFields, $fields);
        }
        $order = null;
        if (!empty($sort) && $sort !== "null") {
            $obj = json_decode($sort);
            $order = array(
                "field" => $sort,
                "direction" => $dir
            );
        }

        $selected = array();
        $items = $this->_modelInstance->loadGrid($page, $rp, $conditions, $order, $selected);
        $data = array(
            "success" => true,
            "total" => $items["results"],
            "rows" => $items["items"],
            "page" => $items["page"]
        );
        $this->layout->printLike(json_encode($data), "json");
    }

    public function getNews(){
        $wallId = $this->input->post("WallId");
        $GrupoId = $this->input->post("GrupoId");
        $page = $this->input->post("Page");
        $rp = $this->input->post("Rp");
        $selected = array();
        $conditions = array(
            array(
                'field'=>'WallId',
                'value'=>$wallId,
                'type'=>'where'
            ),array(
                'field'=>'GrupoId',
                'value'=>$GrupoId,
                'type'=>'where'
            ),
        );
        $items = $this->_modelInstance->loadGrid_nuevo($page, $rp, $conditions, null, null);
        $data = array(
            "success" => true,
            "total" => $items["results"],
            "rows" => $items["items"],
            "page" => $items["page"]
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    
}

